package com.carleasoft.mps.adu.business.user.service.impl;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carleasoft.mps.adu.business.basicsInfo.bean.entity.AuthorityUserBasicInfo;
import com.carleasoft.mps.adu.business.basicsInfo.bean.vo.AuthorityUserInfoVo;
import com.carleasoft.mps.adu.business.basicsInfo.dao.AuthorityUserBasicInfoMapper;
import com.carleasoft.mps.adu.business.basicsInfo.excel.ConvertTemplatePath;
import com.carleasoft.mps.adu.business.basicsInfo.excel.ExcelUtils;
import com.carleasoft.mps.adu.business.dept.bean.vo.DeptDetailVo;
import com.carleasoft.mps.adu.business.dept.dao.DeptDao;
import com.carleasoft.mps.adu.business.user.bean.entity.MAuthorityUserVacation;
import com.carleasoft.mps.adu.business.user.bean.po.MAuthorityUserVacationPo;
import com.carleasoft.mps.adu.business.user.bean.vo.*;
import com.carleasoft.mps.adu.business.user.dao.MAuthorityUserVacationMapper;
import com.carleasoft.mps.adu.common.constants.BusinessErrorEnum;
import com.carleasoft.mps.core.exceptions.BusinessException;
import com.carleasoft.mps.core.user.Constants;
import com.carleasoft.mps.core.user.ThreadUserContext;
import com.carleasoft.mps.core.user.UserCacheData;
import com.carleasoft.mps.core.utils.DateUtil;
import com.carleasoft.mps.core.utils.ExceptionUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.carleasoft.mps.adu.business.user.service.IMAuthorityUserVacationService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 人员休假Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-04-12
 */
@Service
public class MAuthorityUserVacationServiceImpl extends ServiceImpl<MAuthorityUserVacationMapper, MAuthorityUserVacation> implements IMAuthorityUserVacationService
{
    @Autowired
    private MAuthorityUserVacationMapper mAuthorityUserVacationMapper;

    @Autowired
    private AuthorityUserBasicInfoMapper authorityUserBasicInfoMapper;

    @Autowired
    private DeptDao deptDao;

    /**
     * 查询人员休假
     * 
     * @param id 人员休假主键
     * @return 人员休假
     */
    @Override
    public MAuthorityUserVacationVo selectMAuthorityUserVacationById(Integer id)
    {
        return mAuthorityUserVacationMapper.selectMAuthorityUserVacationById(id);
    }

    /**
     * 查询人员休假列表
     * 
     * @param mAuthorityUserVacationPo 人员休假
     * @return 人员休假
     */
    @Override
    public Page<MAuthorityUserVacationVo> selectMAuthorityUserVacationList(Page page, MAuthorityUserVacationPo mAuthorityUserVacationPo)
    {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        page.setCountId("selectPageCount");
        Page<MAuthorityUserVacationVo> voPage = new Page<>();
        if (user.getUserCat() == Constants.ORDINARY_USER) {
            if(StringUtils.isEmpty(user.getDeptCode()) ||
                    (StringUtils.isNotEmpty(mAuthorityUserVacationPo.getDeptCode()) && !mAuthorityUserVacationPo.getDeptCode().equals(user.getDeptCode()))){
                return new Page<>();
            }
            mAuthorityUserVacationPo.setDeptCode(user.getDeptCode());
        }
        return mAuthorityUserVacationMapper.selectMAuthorityUserVacationList(page,mAuthorityUserVacationPo);
    }

    /**
     * 新增人员休假
     * 
     * @param mAuthorityUserVacation 人员休假
     * @return 结果
     */
    @Override
    public boolean insertMAuthorityUserVacation(MAuthorityUserVacation mAuthorityUserVacation)
    {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        AuthorityUserBasicInfo authorityUserBasicInfo = authorityUserBasicInfoMapper.selectOne(Wrappers.<AuthorityUserBasicInfo>lambdaQuery()
                .eq(AuthorityUserBasicInfo::getUserCode, user.getUserCode()));
        if(authorityUserBasicInfo.getUserSubmitFlag() == 0){
            throw ExceptionUtil.create(BusinessErrorEnum.COUNT_NO_JURISDICTION);
        }
        mAuthorityUserVacation.setCreatePersonCode(user.getUserCode());
        mAuthorityUserVacation.setCreatePersonName(user.getUserName());
        mAuthorityUserVacation.setCreateTime(LocalDateTime.now());
        return this.save(mAuthorityUserVacation);
    }

    /**
     * 根据部门Code分钟求和总条数
     * @return
     */
    @Override
    public List<MAuthorityDeptCountVo> selectMAuthorityDeptCountByDeptCode() {
        return mAuthorityUserVacationMapper.selectMAuthorityDeptCountByDeptCode(DateUtil.getDate());
    }

    /**
     * 修改人员休假
     * 
     * @param mAuthorityUserVacation 人员休假
     * @return 结果
     */
    @Override
    public boolean updateMAuthorityUserVacation(MAuthorityUserVacation mAuthorityUserVacation)
    {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        mAuthorityUserVacation.setUpdatePersonCode(user.getUserCode());
        mAuthorityUserVacation.setUpdatePersonName(user.getUserName());
        mAuthorityUserVacation.setUpdateTime(LocalDateTime.now());
        return this.updateById(mAuthorityUserVacation);
    }

    /**
     * 删除人员休假信息
     * 
     * @param id 人员休假主键
     * @return 结果
     */
    @Override
    public boolean deleteMAuthorityUserVacationById(Integer id)
    {
        return this.removeById(id);
    }

    /**
     * 导入人员休假
     * @param file
     * @return
     */
    @Override
    public boolean userDynamicExcel(MultipartFile file) {
        boolean isOk = false;
        List<MAuthorityUserVacationExcelVo> list = null;
        try {
            list = ExcelUtils.importExcel(file, MAuthorityUserVacationExcelVo.class);
            list = list.stream().filter(i -> i.getUserName() != null).collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (CollUtil.isNotEmpty(list)){
            Set<String> userNames = list.stream().map(MAuthorityUserVacationExcelVo::getUserName).collect(Collectors.toSet());
            List<AuthorityUserInfoVo> userInfoVos = authorityUserBasicInfoMapper.getUserInfoByUserNames(userNames);
            Map<String, AuthorityUserInfoVo> userMap = userInfoVos.stream().collect(Collectors.toMap(AuthorityUserInfoVo::getUserName, Function.identity()));
            //单位信息
            Set<String> deptNames = list.stream().map(MAuthorityUserVacationExcelVo::getDeptName).collect(Collectors.toSet());
            List<DeptDetailVo> deptInfoVos = deptDao.getDeptInfoByDeptNames(deptNames);
            Map<String, DeptDetailVo> deptMap = deptInfoVos.stream().collect(Collectors.toMap(DeptDetailVo::getDeptName, Function.identity()));
            for (MAuthorityUserVacationExcelVo vacationExcelVo : list) {
                DeptDetailVo deptDetailVo = deptMap.get(vacationExcelVo.getDeptName());
                AuthorityUserInfoVo userInfoVo = userMap.get(vacationExcelVo.getUserName());
                MAuthorityUserVacation vacation = new MAuthorityUserVacation();
                vacation.setDeptCode(deptDetailVo.getDeptCode());
                vacation.setUserCode(userInfoVo.getUserCode());
                vacation.setSumDay(vacationExcelVo.getSumDay());
                vacation.setPathDay(vacationExcelVo.getPathDay());
                vacation.setAddRestDay(vacationExcelVo.getAddRestDay());
                vacation.setAlreadyRestDay(vacationExcelVo.getAlreadyRestDay());
                vacation.setResidueDay(vacationExcelVo.getResidueDay());
                vacation.setLeaveDay(vacationExcelVo.getLeaveDay());
                vacation.setNqingDay(vacationExcelVo.getNqingDay());
                vacation.setLeaveAddress(vacationExcelVo.getLeaveAddress());
                vacation.setLeaveStartTime(vacationExcelVo.getLeaveStartTime());
                vacation.setLeaveEndTime(vacationExcelVo.getLeaveEndTime());
                vacation.setOfficersBattalion(vacationExcelVo.getOfficersBattalion());
                vacation.setRemark(vacationExcelVo.getRemark());
                isOk = this.insertMAuthorityUserVacation(vacation);
            }
        }

        return isOk;
    }

    /**
     * 导出人员休假
     * @param startTime
     * @param response
     * @return
     */
    @Override
    public boolean export(HttpServletResponse response,String startTime) throws ParseException {
        MAuthorityUserVacationPo mAuthorityUserVacationPo = new MAuthorityUserVacationPo();
        Page<MAuthorityUserVacationVo> mAuthorityUserVacationVoPage = new Page<>();
        mAuthorityUserVacationPo.setSize(9999);
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        Date date = ft.parse(startTime);
        String month = DateUtil.getTimeStr(date, "MM");
        String day = DateUtil.getTimeStr(date, "dd");
        int week = 0;
        if(Integer.valueOf(day) < 8){
            week = 1;
        }else if(Integer.valueOf(day) >= 8 && Integer.valueOf(day) < 15){
            week = 2;
        }else if(Integer.valueOf(day) >= 15 && Integer.valueOf(day) < 22){
            week = 3;
        }else if(Integer.valueOf(day) >= 22 && Integer.valueOf(day) < 29){
            week = 4;
        }else if(Integer.valueOf(day) >= 29 && Integer.valueOf(day) < 31){
            week = 5;
        }
        mAuthorityUserVacationPo.setCreateTimeStart(date);
        String after = DateUtil.getSpecifiedDayAfter(startTime, 6);
        Date afterDate = ft.parse(after);
        Calendar rCalendar = Calendar.getInstance();
        rCalendar.setTime(afterDate);
        rCalendar.add(Calendar.HOUR,23);
        rCalendar.add(Calendar.MINUTE,59);
        rCalendar.add(Calendar.SECOND,59);
        mAuthorityUserVacationPo.setCreateTimeEnd(rCalendar.getTime());
        mAuthorityUserVacationVoPage = this.selectMAuthorityUserVacationList(new Page(mAuthorityUserVacationPo.getCurrent(), mAuthorityUserVacationPo.getSize()),mAuthorityUserVacationPo);
        if (CollUtil.isEmpty(mAuthorityUserVacationVoPage.getRecords())) {
            throw new BusinessException("1008611", "没有数据不允许导出");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<ImportUserVacationExcelVo> importUserVacationExcelVoList = new ArrayList<>();
        int index = 1;
        for (MAuthorityUserVacationVo vo : mAuthorityUserVacationVoPage.getRecords()){
            ImportUserVacationExcelVo importUserVacationExcelVo = new ImportUserVacationExcelVo();
            BeanUtils.copyProperties(vo,importUserVacationExcelVo);
            importUserVacationExcelVo.setLeaveStartTime(simpleDateFormat.format(vo.getLeaveStartTime()));
            importUserVacationExcelVo.setLeaveEndTime(simpleDateFormat.format(vo.getLeaveEndTime()));
            importUserVacationExcelVo.setIndex(index);
            importUserVacationExcelVoList.add(importUserVacationExcelVo);
            index++;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list", importUserVacationExcelVoList);
        map.put("month",month);
        map.put("week",week);
        String path = "\\template\\userVacationExport.xls";
        String fileName = month + "月" + ",第"+week+"周人员休假数据";
        TemplateExportParams templatePath = new TemplateExportParams(ConvertTemplatePath.convertTemplatePath(path));
        try {
            ExcelUtils.exportExcel(templatePath, map, fileName, response);
        } catch (IOException e) {
        }
        return true;
    }
}
